package cn.dankal.flyaudio.current.post.detail;

import android.content.Context;
import android.graphics.Rect;
import android.os.Handler;

import androidx.core.widget.NestedScrollView;
import androidx.recyclerview.widget.DividerItemDecoration;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import android.view.MotionEvent;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
import android.widget.EditText;

import com.alibaba.android.arouter.launcher.ARouter;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;
import cn.dankal.basiclib.DKUserManager;
import cn.dankal.basiclib.DankalApplication;
import cn.dankal.basiclib.base.activity.BaseStateActivity;
import cn.dankal.basiclib.protocol.LoginProtocol;
import cn.dankal.basiclib.util.KeyboardChangeListener;
import cn.dankal.basiclib.util.ScreenUtils;
import cn.dankal.basiclib.util.SoftKeyboardUtil;
import cn.dankal.basiclib.util.StringUtil;
import cn.dankal.basiclib.util.ToastUtils;
import cn.dankal.basiclib.widget.swipetoloadlayout.SwipeToLoadLayout;
import cn.dankal.business.pojo.BaseBeanList;
import cn.dankal.business.pojo.CommentBean;
import cn.dankal.business.pojo.CurrentBean;
import cn.dankal.business.pojo.InfoBean;
import cn.dankal.business.pojo.ReasonBean;
import cn.dankal.flyaudio.R;

import static androidx.recyclerview.widget.DividerItemDecoration.VERTICAL;


/**
 * 帖子详情
 */
public class PostDetailActivity extends BaseStateActivity implements Contract.View {

    // 评论列表
    @BindView(R.id.rv_post_comments)
    RecyclerView mRvPostComments;

    // 输入编辑
    @BindView(R.id.et_content)
    EditText mEtContent;

    @BindView(R.id.ll_comment)
    View mInBottomInput;

    @BindView(R.id.swipe_toload_layout)
    SwipeToLoadLayout mSwipeToLoadLayout;

    protected String postId;

    private boolean isFirst = true;//第一次布局改变

    private boolean isRefresh = true;

    private int distance;

    private boolean isOpen = false;


    protected Contract.Presenter mPresenter;
    protected CommentAdapter mAdapter;

    private KeyboardChangeListener keyboardChangeListener;

    protected String commentName;
    protected String commentUuid;
    protected int commentPosition = -1;
    protected String recevierUuid;
    //是否是评论的刷新
    private boolean isComment;

    private View mView = null;

    private int mY;

    @BindView(R.id.swipe_target)
    NestedScrollView nestedScrollView;

    private LinearLayoutManager linearLayoutManager;


    @Override
    public int getLayoutId() {
        return R.layout.activity_current_detail;
    }


    @Override
    public void initComponents() {
        mPresenter = new Presenter();
        mPresenter.attachView(this);

        keyboardChangeListener = new KeyboardChangeListener(this);
        keyboardChangeListener.setKeyBoardListener((isShow, keyboardHeight) -> {
            if (!isShow) {
                hideBottomInput();
            }
        });

        mSwipeToLoadLayout.setLoadMoreEnabled(false);
        mSwipeToLoadLayout.setRefreshEnabled(true);

        mSwipeToLoadLayout.setOnRefreshListener(this::onRefresh);
        mSwipeToLoadLayout.setOnLoadMoreListener(this::onLoadMore);
        linearLayoutManager = new LinearLayoutManager(this);
        mRvPostComments.setLayoutManager(linearLayoutManager);
        mRvPostComments.setNestedScrollingEnabled(false);
        mAdapter = new CommentAdapter(true);
        mAdapter.setHasStableIds(true);
        mAdapter.setListener(new CommentReplyAdapter.OnChoiceByUserToReplyListener() {
            @Override
            public void innerComment(String name, String comment_id, String userId, int position) {
                onInnerCommentClick(name, comment_id, userId, position);
            }

            @Override
            public void praise(String uuid, String type, int position) {
                ToastUtils.showShort("点赞成功");
                // 局部刷新 点赞的UI
                if (mAdapter != null && mAdapter.getDatas() != null && mAdapter.getDatas().size() > position) {
                    // 是否点赞：是>=1 否0
                    if (mAdapter.getDatas().get(position).isPraise > 0) {
                        mAdapter.getDatas().get(position).isPraise = 0;
                        int likeCount;
                        try {
                            likeCount = Integer.valueOf(mAdapter.getDatas().get(position).likeNumber);
                        } catch (Exception e) {
                            likeCount = 1;
                        }
                        mAdapter.getDatas().get(position).likeNumber = String.valueOf(likeCount - 1);
                    } else {
                        mAdapter.getDatas().get(position).isPraise = 1;
                        int likeCount;
                        try {
                            likeCount = Integer.valueOf(mAdapter.getDatas().get(position).likeNumber);
                        } catch (Exception e) {
                            likeCount = 1;
                        }
                        mAdapter.getDatas().get(position).likeNumber = String.valueOf(likeCount + 1);
                    }
                    mAdapter.notifyItemChanged(position, "star");
                }
                mPresenter.praise(uuid, type, position);
            }

            @Override
            public void praiseCancel(String uuid, String type, int position) {
                ToastUtils.showShort("点赞取消");
                // 局部刷新 点赞的UI
                if (mAdapter != null && mAdapter.getDatas() != null && mAdapter.getDatas().size() > position) {
                    // 是否点赞：是>=1 否0
                    if (mAdapter.getDatas().get(position).isPraise > 0) {
                        mAdapter.getDatas().get(position).isPraise = 0;
                        int likeCount;
                        try {
                            likeCount = Integer.valueOf(mAdapter.getDatas().get(position).likeNumber);
                        } catch (Exception e) {
                            likeCount = 1;
                        }
                        mAdapter.getDatas().get(position).likeNumber = String.valueOf(likeCount - 1);
                    } else {
                        mAdapter.getDatas().get(position).isPraise = 1;
                        int likeCount;
                        try {
                            likeCount = Integer.valueOf(mAdapter.getDatas().get(position).likeNumber);
                        } catch (Exception e) {
                            likeCount = 1;
                        }
                        mAdapter.getDatas().get(position).likeNumber = String.valueOf(likeCount + 1);
                    }
                    mAdapter.notifyItemChanged(position, "star");
                }
                mPresenter.praiseCancel(uuid, type, position);
            }
        });
        mRvPostComments.setAdapter(mAdapter);

        mRvPostComments.addItemDecoration(new DividerItemDecoration(this, VERTICAL));

        mEtContent.setOnFocusChangeListener((v, hasFocus) -> {
            if (!hasFocus) {
                SoftKeyboardUtil.hideSoftInput(v);
            }
            isFirst = false;
        });

        mAdapter.setViewClickListen((y) -> {
            mY = y;
        });

        SoftKeyBoardListener.setListener(this, new SoftKeyBoardListener.OnSoftKeyBoardChangeListener() {
            @Override
            public void keyBoardShow(int height) {
                if (isOpen) {
                    return;
                }
                isOpen = true;
                //Toast.makeText(getActivity(), "键盘显示 高度" + height, Toast.LENGTH_SHORT).show();
                Rect r = new Rect();
                //获取当前界面可视部分
                PostDetailActivity.this.getWindow().getDecorView().getWindowVisibleDisplayFrame(r);
                //获取屏幕的高度
                int screenHeight = PostDetailActivity.this.getWindow().getDecorView().getRootView().getHeight();

                if (mY > (screenHeight / 2)) {//点击的是屏幕下部分
                    //此处就是用来获取键盘的高度的， 在键盘没有弹出的时候 此高度为0 键盘弹出的时候为一个正数
                    int heightDifference = screenHeight - r.bottom;
                    //nestedScrollView需要滚动的距离是键盘的高度-手指在屏幕下部分的Y坐标
                    distance = (mY - (screenHeight / 2)) + 300;
                    nestedScrollView.scrollBy(0, distance);
                } else {
                    distance = 0;
                }
            }

            @Override
            public void keyBoardHide(int height) {
                if (!isOpen) {
                    return;
                }
                isOpen = false;
            }
        });
    }

    public void initData(String uuid) {
        postId = uuid;
        if (!StringUtil.isValid(postId)) {
            ToastUtils.showShort("没有uuid");
            postDelayedToFinish();
            return;
        }
        mPresenter.setUuid(postId);
        mPresenter.onRefresh();
    }

    protected void onInnerCommentClick(String name, String comment_id, String userId, int commentPosition) {

        PostDetailActivity.this.commentName = name;
        PostDetailActivity.this.commentUuid = comment_id;
        PostDetailActivity.this.recevierUuid = userId;
        PostDetailActivity.this.commentPosition = commentPosition;
        showShortBottomInput();
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        if (mPresenter != null) {
            mPresenter.detachView();
        }
        keyboardChangeListener.destroy();
    }


    //发送
    @OnClick(R.id.tv_send)
    public void onViewClicked(View view) {
        if (!DankalApplication.isLogin()) {
            ARouter.getInstance().build(LoginProtocol.LOGIN).navigation();
            return;
        }
        if (DKUserManager.getUserInfo().getUserUuid().equals(recevierUuid)) {
            ToastUtils.showShort("不能评论自己帖子");
            return;
        }

        int et_content_count = mEtContent.getText().length();
        if (et_content_count > 200) {
            ToastUtils.showShort("帖子评论字符限制长度200");
            return;
        }
        String content = mEtContent.getText().toString();
        if (this.commentUuid != null) {
            mPresenter.inside_comment(commentUuid, content, recevierUuid, postId);
            return;
        }
        mPresenter.comment(content, postId);
    }

    @Override
    public boolean dispatchTouchEvent(MotionEvent ev) {
        if (ev.getAction() == MotionEvent.ACTION_DOWN) {
            float rawX = ev.getRawX();
            float rawY = ev.getRawY();
            if (!ScreenUtils.calcViewScreenLocation(mInBottomInput).contains(rawX, rawY)) {
                if (SoftKeyboardUtil.isKeyboardShown(mEtContent)) {
                    SoftKeyboardUtil.hideSoftInput(mEtContent);
                } else {
                    hideBottomInput();
                }
            }
        }
        return super.dispatchTouchEvent(ev);
    }

    private void showShortBottomInput() {

        SoftKeyboardUtil.showSoftInput(mInBottomInput);

    }


    private void hideBottomInput() {

        SoftKeyboardUtil.hideSoftInput(mInBottomInput);

    }

    @Override
    public void onCommentList(BaseBeanList<CommentBean> commentBeanBaseBeanList) {
        new Handler().postDelayed(new Runnable() {
            @Override
            public void run() {
                mSwipeToLoadLayout.setRefreshing(false);
                mSwipeToLoadLayout.setLoadingMore(false);
                mAdapter.addDatas(commentBeanBaseBeanList.list, isRefresh);
            }
        }, 600);

        List<View> list = new ArrayList<>();
        list.add(mEtContent);
        SoftKeyboardUtil.hideSoftKeyboard(PostDetailActivity.this, list);

        if (!isFirst) {
            //ToastUtils.showShort("刷新成功！");
        }


        if (isComment) {
            isComment = false;
            nestedScrollView.smoothScrollTo(0, (int) ScreenUtils.calcViewScreenLocation(findViewById(R.id.iv_tag)).top);
        }
    }

    @Override
    public void onPraiseResult(ReasonBean bodyCase, int position) {

    }

    @Override
    public void onInnerCommentResult(ReasonBean commentCase) {
        mSwipeToLoadLayout.setRefreshing(false);
        mSwipeToLoadLayout.setLoadingMore(false);
        ToastUtils.showShort(commentCase.reason);
    }

    @Override
    public void onCommentResult(ReasonBean reasonBean, CommentBean commentBean) {
        commentName = null;
        commentUuid = null;
        recevierUuid = null;
        hideBottomInput();
        isComment = true;
        // 如果有位置就在评论的位置插入一条数据
        if (commentPosition != -1 && mAdapter != null && mAdapter.getDatas().size() >= commentPosition) {
            /* 局部刷新数据 */
            CommentBean baseComment = mAdapter.getDatas().get(commentPosition);
            CommentBean.SecondCommentsBean newInsertComment = new CommentBean.SecondCommentsBean();
            newInsertComment.commentUuid = commentBean.uuid;
            newInsertComment.content = commentBean.content;
            newInsertComment.sendName = commentBean.name;
            newInsertComment.receiveName = baseComment.name;
            mAdapter.getDatas().get(commentPosition).list.add(newInsertComment);
            mAdapter.notifyItemChanged(commentPosition);
            mRvPostComments.scrollToPosition(commentPosition);
            commentPosition = -1;
            hideKeyboard();
        } else {
            onRefresh();
        }
    }

    private void hideKeyboard() {
        InputMethodManager imm = (InputMethodManager) this.getSystemService(Context.INPUT_METHOD_SERVICE);
        if (imm.isActive()) {
            if (this.getCurrentFocus().getWindowToken() != null) {
                imm.hideSoftInputFromWindow(this.getCurrentFocus().getWindowToken(), InputMethodManager.HIDE_NOT_ALWAYS);
            }
        }
    }


    @Override
    public void onInfoDetailResult(InfoBean infoBean) {

    }

    @Override
    public void onCurrentDetailResult(CurrentBean currentBean) {

    }

    private void onLoadMore() {
        isRefresh = false;
        mPresenter.onLoadMore();
    }

    private void onRefresh() {
        isRefresh = true;
        //mAdapter.clearData();
        mPresenter.onRefresh();
    }

    @Override
    public Object contentView() {
        return findViewById(R.id.ll_detail);
    }


}
